###
  产品
  ###

_ = require 'underscore'
ProductApp = require '../db/ProductApp'

module.exports = (app) ->

  #查询所有产品
  app.get '/admin/products', (req, res, next) ->
    ProductApp.findAll (err, data) ->
       return res.status(404).json {code:-1, message:'Can\'t find products.'} if err
       res.status(200).json {code: 0, data: data}

  #分页查询产品
  app.get '/admin/products/:page/:limit', (req, res, next) ->
    console.log 2
    keyword = req.query.keyword || ""
    page = 1
    limit= 10
    query_obj = if req.query.name then {name: new RegExp(req.query.name)} else {}
    new Promise (resolve, reject) ->
      page = +req.params.page
      limit = +req.params.limit
      ProductApp.count query_obj, (err, count) ->
         return reject(err) if err
         resolve(count)
    .then (count) ->
      new Promise (resolve, reject) ->
        #按照name 模糊查询
        ProductApp.list page, limit, keyword, query_obj, (err, data) ->
           return reject(err) if err
           res.status(200).json {code:0, data: data, total: count}
    .catch (err) ->
      return res.status(404).json {code:-1, message:'Can\'t find products.'}

  #查询产品 by id
  app.get '/admin/products/:ProductApp_id', (req, res, next) ->
    ProductApp.findOne _id: req.params.ProductApp_id, (err, data) ->
       return res.status(404).json {code:-1, message:'Can\'t find products.'} if err
       res.status(200).json {code: 0, data: data}

  #删除产品 by id
  app.delete '/admin/products/:ProductApp_id', (req, res, next) ->
    new Promise (resolve, reject) ->
      ProductApp.findOneAndRemove _id: req.params.ProductApp_id, (err, obj) ->
        return reject(err) if err
        resolve(obj)
    .then (data) ->
      res.status(200).json {code: 0, data: 'delete successfully'}
    .catch (err) ->
      console.log err
      res.status(404).json {code:-1, message:'delete Failed'}

  #更新产品 by id
  app.put '/admin/products/:ProductApp_id', (req, res, next) ->
    update =  _.pick(req.body, ['name', 'version', 'introduction'])
    ProductApp.findOneAndUpdate _id: req.params.ProductApp_id, update, (err, data) ->
       return res.status(404).json {code:-1, message:'Can\'t find products.'} if err
       res.status(200).json {code: 0, data: 'update successfully'}

  # 增加产品
  app.post '/admin/products', (req, res, next) ->
    _ProductApp = _.pick(req.body, ['name', 'version', 'introduction'])
    new Promise (resolve, reject) ->
      ProductApp.save _ProductApp, (err, obj) ->
        return reject(err) if err
        resolve(obj)
    .then (data) ->
      res.status(200).json({code: 0, msg: "successfully", data: data})
    .catch (err) ->
      console.log err
      res.status(404).json {code:-1, message:'add Failed'}
